package dongze.com.ckdj.activity;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.ViewGroup;

import dongze.com.ckdj.R;
import dongze.com.ckdj.databinding.ProcessingBinding;
import dongze.com.ckdj.databinding.model.ProcessingModel;

/**
 * Created by fanqwz on 2017/9/4.
 */

public class ProgressableActivity extends BaseActivity {
    Handler handler;
    int processCount = 0;
    private ProcessingModel processingModel = new ProcessingModel();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler(Looper.getMainLooper());
        ProcessingBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.processing, null, false);
        binding.setVisible(processingModel);
        getWindow().addContentView(binding.getRoot(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    @Override
    protected void onDestroy() {
        if (processCount > 0) {
            getWindow().getDecorView().setEnabled(true);
            processingModel.visible.set(false);
        }

        super.onDestroy();
    }

    public void doProcessing() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                processCount++;

                if (processCount > 0) {
                    getWindow().getDecorView().clearFocus();
                    getWindow().getDecorView().setEnabled(false);
                    processingModel.visible.set(true);
                }
            }
        });
    }

    public void finishProcessing() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                processCount--;

                if (processCount <= 0) {
                    getWindow().getDecorView().setEnabled(true);
                    processingModel.visible.set(false);
                }
            }
        });
    }

}
